#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import sys

from flask_script import Server, Manager, prompt_bool, Shell
from pitaya import app


manager = Manager(app)
manager.add_command("runserver", Server('0.0.0.0', port=5000))


@manager.command
def createall():
    "Creates database tables"
    from models.model import db, Category, User
    db.create_all()
    "add Category"
    lists = [u'PYTHON', u'编程珠玑', u'数据库', u'操作系统', u"杂项"]
    for i in range(1, 6):
        item = Category()
        item.id = i
        item.category_name = lists[i-1]
        db.session.add(item)
    user = User()
    user.name = 'admin'
    user.password = '0a0c0057c13130bee1613976a608c0c5'
    db.session.add(user)
    db.session.commit()


@manager.command
def dropall():
    "Drops all database tables"
    from models.base import db
    if prompt_bool("Are you sure ? You will lose all your data !"):
        db.drop_all()


# @app.teardown_request
# def teardown_request(exception):
#     print "----close mysql conn-----"
#     app.logger.error(exception)
#     conn_mysql.remove()
#     if exception and conn_mysql.is_active:
#         conn_mysql.rollback()


def make_shell_context():
    return dict(app=app)


manager.add_command('shell', Shell(make_context=make_shell_context))
if __name__ == "__main__":
    logfile = "./pitaya.log"
    app.debug = True
    logging.basicConfig(filename=logfile, level=logging.INFO)
    logger = logging.getLogger('werkzeug')
    logger.setLevel(logging.INFO)
    manager.run()
